<template>
  <div class="data-view-container">
    <!-- 搜索框 -->
    <el-autocomplete
      v-model="searchQuery"
      :fetch-suggestions="fetchSuggestions"
      placeholder="请输入问题名称进行搜索"
      class="search-input"
      clearable
      @clear="handleSearch"
      @keyup.enter="handleSearch"
      @select="handleSuggestionSelect" 
    >
      <template #prepend>
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </template>
    </el-autocomplete>

    <!-- 加载状态 -->
    <el-skeleton v-if="loading" :rows="6" animated />

    <!-- 数据表格 -->
    <el-table v-else :data="data" border style="width: 100%" class="data-table">
      <el-table-column prop="_id" label="ID" width="180" />
      <el-table-column prop="problem" label="问题" width="180" />
      <el-table-column prop="description" label="描述" />

      <!-- 步骤 -->
      <el-table-column label="步骤">
        <template #default="{ row }">
          <el-collapse>
            <el-collapse-item
              v-for="(step, index) in row.steps"
              :key="index"
              :title="`步骤 ${index + 1}: ${step.title}`"
            >
              <div class="step-details">
                <p><strong>标题:</strong> {{ step.title }}</p>
                <p><strong>详情:</strong> {{ step.details }}</p>
                <p><strong>角色:</strong> {{ step.role }}</p>
                <div v-if="step.actions && step.actions.length > 0">
                  <p><strong>操作:</strong></p>
                  <ul>
                    <li v-for="(action, actionIndex) in step.actions" :key="actionIndex">
                      <p><strong>操作详情:</strong> {{ action.detail }}</p>
                      <p><strong>类型:</strong> {{ action.action }}</p>
                      <p><strong>内容:</strong> {{ action[action.action] }}</p>
                    </li>
                  </ul>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </template>
      </el-table-column>

      <!-- 附加说明 -->
      <el-table-column label="附加说明">
        <template #default="{ row }">
          <el-collapse>
            <el-collapse-item
              v-for="(note, index) in row.additional_notes"
              :key="index"
              :title="`说明 ${index + 1}`"
            >
              <div class="note-details">
                <p>{{ note }}</p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-link type="primary" :underline="false" :href="`/tpa/data-edit/${row._id}`">
            编辑
          </el-link>
          <el-button
            v-if="isAdmin"
            type="danger"
            size="mini"
            style="margin-left: 10px;"
            @click="deleteData(row._id)"
          >
            删除
          </el-button>
          <el-tooltip v-else content="无权限删除数据" placement="top">
            <el-button type="danger" size="mini" style="margin-left: 10px;" disabled>
              删除
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      :current-page="page"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next"
      @current-change="handlePageChange"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: [], // 表格数据
      total: 0, // 数据总数
      page: 1, // 当前页码
      pageSize: 10, // 每页条数
      loading: true, // 加载状态
      searchQuery: '', // 搜索关键词
      isAdmin: false, // 是否为管理员
      searchResults: [], // 搜索建议列表
    };
  },
  created() {
    this.checkAdminStatus();
    this.fetchData();
  },
  methods: {
    // 检查用户是否为管理员
    checkAdminStatus() {
      const is_admin = localStorage.getItem('is_admin'); // 从本地存储获取权限
      this.isAdmin = is_admin === 'true'; // 确保布尔值正确
    },
    // 获取数据
    async fetchData() {
      this.loading = true;
      try {
        const response = await this.$request.get('/tpa/api/view_data/', {
          params: {
            page: this.page,
            pageSize: this.pageSize,
            problem_name: this.searchQuery, // 搜索关键词
          },
        });
        this.data = response.data;
        this.total = response.total;
      } catch (error) {
        console.error('Error fetching data:', error);
        this.$message.error('数据加载失败');
      } finally {
        this.loading = false;
      }
    },
    // 获取搜索建议
    async fetchSuggestions(query, callback) {
  if (!query) {
    return callback([]);
  }
  try {
    const response = await this.$request.get('/es/es_search/', {
      params: { q: query }
    });
    
    this.searchResults = response.data.map(item => ({
      value: item.problem, // el-autocomplete 需要一个 `value` 字段
      id: item.id, // 存储 ID，方便后续使用
    }));

    callback(this.searchResults); // 确保调用回调函数，更新下拉列表
  } catch (error) {
    console.error('Error fetching suggestions:', error);
    callback([]); // 遇到错误时返回空数组，避免 UI 崩溃
  }
},
  // 选择搜索建议后立即搜索
  handleSuggestionSelect(item) {
    this.searchQuery = item.value; // 更新搜索框内容
    this.handleSearch(); // 立即搜索
  },
    // 搜索
    handleSearch() {
      this.page = 1; // 重置页码
      this.fetchData();
    },
    // 分页
    handlePageChange(page) {
      this.page = page;
      this.fetchData();
    },
    // 删除数据
    async deleteData(id) {
      try {
        // 确认删除
        await this.$confirm('确定要删除此数据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });

        // 调用删除接口
        const response = await this.$request.delete(`/tpa/api/delete/?id=${id}`);
        if (response.status === 'success') {
          this.$message.success('数据删除成功');
          this.fetchData(); // 重新加载数据
        } else {
          this.$message.error('数据删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除数据失败');
          console.error(error);
        }
      }
    },
  },
};
</script>


<style scoped>
.data-view-container {
  padding: 20px;
}

.search-input {
  margin-bottom: 20px;
  width: 300px;
}

.data-table {
  margin-bottom: 20px;
}

.pagination {
  text-align: right;
}

.step-details,
.note-details {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin: 5px 0;
}

.step-details p,
.note-details p {
  margin: 5px 0;
}

.el-collapse {
  border: none;
}

.el-collapse-item {
  margin-bottom: 10px;
}

.el-collapse-item__header {
  font-weight: bold;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

.el-collapse-item__content {
  padding: 10px;
}
</style>